<%--
  Created by IntelliJ IDEA.
  User: 22954
  Date: 2024/8/31
  Time: 14:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>计算器</title>
</head>
<body>
<%
    String[] warnings = (String[]) request.getAttribute("warning");
    String num1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
    String num2 = request.getParameter("num2") == null ? "" : request.getParameter("num2");
%>
<h1>Jsp版-计算器</h1>
<form action="<%=request.getContextPath() + "/calServlet"%>"
      method="post"
      onsubmit="return check()">
    <label>
        num1: <input type="text" id="num1" name="num1" value="<%=num1%>">
        <%
            if (warnings != null && warnings[0] != null) {
        %>
        <%=warnings[0]%>
        <%
            }
        %><br/><br/>
        num2: <input type="text" id="num2" name="num2" value="<%=num2%>">
        <%
            if (warnings != null && warnings[1] != null) {
        %>
        <%=warnings[1]%>
        <%
            }
        %><br/><br/>
        <select name="operator">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
        </select>
        <%
            if (warnings != null && warnings[2] != null) {
        %>
        <%=warnings[2]%>
        <%
            }
        %><br/><br/>
        <input type="submit" value="计算">
    </label>
</form>
<script type="text/javascript">
    function check() {
        var num1 = document.getElementById("num1").value;
        var num2 = document.getElementById("num2").value;
        var regex = /^[-]?([1-9]\d*|0)$/;
        var ret = true;
        var warning = "";
        if (!regex.test(num1)) {
            warning += "num1不是整数\n";
            ret = false;
        }
        if (!regex.test(num2)) {
            warning += "num2不是整数";
            ret = false;
        }
        if (warning.length > 0) {
            alert(warning);
        }
        return ret;
    }
</script>
</body>
</html>
